import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  IComponent, 
  IPageConfig, 
  IWidgetMeta, 
  IDragState, 
  ISelectionState,
  IHistoryRecord,
  IProject
} from '@/types/designer'

export const useDesignerStore = defineStore('designer', () => {
  // 当前项目
  const currentProject = ref<IProject | null>(null)
  
  // 当前页面
  const currentPage = ref<IPageConfig | null>(null)
  
  // 组件库
  const widgetLibrary = ref<IWidgetMeta[]>([
    {
      type: 'text',
      name: '文本组件',
      icon: 'el-icon-document',
      category: '基础组件',
      description: '用于显示文本内容',
      defaultProps: {
        text: '示例文本',
        fontSize: 14,
        color: '#333333',
        fontWeight: 'normal'
      },
      defaultStyle: {
        width: 'auto',
        height: 'auto',
        padding: '8px',
        margin: '0px'
      },
      propSchema: [
        {
          key: 'text',
          label: '文本内容',
          type: 'textarea',
          defaultValue: '示例文本',
          required: true
        },
        {
          key: 'fontSize',
          label: '字体大小',
          type: 'number',
          defaultValue: 14
        },
        {
          key: 'color',
          label: '文字颜色',
          type: 'color',
          defaultValue: '#333333'
        }
      ],
      styleSchema: [
        {
          key: 'width',
          label: '宽度',
          type: 'string',
          defaultValue: 'auto'
        },
        {
          key: 'height',
          label: '高度',
          type: 'string',
          defaultValue: 'auto'
        }
      ]
    },
    {
      type: 'button',
      name: '按钮组件',
      icon: 'el-icon-thumb',
      category: '基础组件',
      description: '可点击的按钮组件',
      defaultProps: {
        text: '按钮',
        type: 'primary',
        size: 'default'
      },
      defaultStyle: {
        width: 'auto',
        height: 'auto',
        padding: '8px 16px'
      },
      propSchema: [
        {
          key: 'text',
          label: '按钮文本',
          type: 'string',
          defaultValue: '按钮',
          required: true
        },
        {
          key: 'type',
          label: '按钮类型',
          type: 'select',
          defaultValue: 'primary',
          options: [
            { label: '主要', value: 'primary' },
            { label: '成功', value: 'success' },
            { label: '警告', value: 'warning' },
            { label: '危险', value: 'danger' }
          ]
        }
      ],
      styleSchema: [
        {
          key: 'width',
          label: '宽度',
          type: 'string',
          defaultValue: 'auto'
        }
      ]
    }
  ])
  
  // 拖拽状态 - 现在由 useDragDropManager 统一管理
  // const dragState = ref<IDragState>({
  //   isDragging: false,
  //   dragComponent: undefined,
  //   dragSource: undefined,
  //   dropTarget: undefined
  // })
  
  // 选中状态
  const selectionState = ref<ISelectionState>({
    selectedComponent: undefined,
    selectedComponents: [],
    isMultiSelect: false
  })
  
  // 历史记录
  const history = ref<IHistoryRecord[]>([])
  const historyIndex = ref(-1)
  
  // 计算属性
  const canUndo = computed(() => historyIndex.value > 0)
  const canRedo = computed(() => historyIndex.value < history.value.length - 1)
  const availableWidgets = computed(() => widgetLibrary.value)
  
  // 根据组件类型获取组件配置
  const getWidgetSchema = (componentType: string) => {
    return widgetLibrary.value.find(widget => widget.type === componentType)
  }
  
  // 添加组件到页面
  const addComponent = (component: IComponent, parentId?: string) => {
    if (!currentPage.value) return null
    
    const now = new Date().toISOString()
    const newComponent = { 
      ...component, 
      id: generateId(),
      createdAt: component.createdAt || now,
      updatedAt: now
    }
    
    if (parentId) {
      // 添加到指定父组件
      addComponentToParent(currentPage.value.components, parentId, newComponent)
      const parent = findComponent(currentPage.value.components, parentId)
      if (parent && parent.children) {
        sortComponentsInPlace(parent.children)
        applyZIndexSequentially(parent.children)
      }
    } else {
      // 添加到根级别，根据位置进行智能排序
      const components = currentPage.value.components
      
      // 如果新组件有位置信息，按位置排序插入
      if (newComponent.style && newComponent.style.top !== undefined) {
        const insertIndex = components.findIndex(existing => {
          const existingTop = parseInt(existing.style?.top || '0')
          const newTop = parseInt(newComponent.style?.top || '0')
          return newTop < existingTop
        })
        if (insertIndex === -1) {
          components.push(newComponent)
        } else {
          components.splice(insertIndex, 0, newComponent)
        }
      } else {
        components.push(newComponent)
      }
      // 统一排序与层级
      sortComponentsInPlace(components)
      applyZIndexSequentially(components)
    }
    
    // 记录历史
    addHistory('add_component', { component: newComponent, parentId })
    
    // 选中新添加的组件
    selectComponent(newComponent)
    
    return newComponent
  }
  
  // 删除组件
  const removeComponent = (componentId: string) => {
    if (!currentPage.value) return
    
    const component = findComponent(currentPage.value.components, componentId)
    if (!component) return
    
    // 记录历史
    addHistory('remove_component', { component })
    
    // 从页面中移除
    removeComponentFromPage(currentPage.value.components, componentId)
    
    // 清除选中状态
    if (selectionState.value.selectedComponent?.id === componentId) {
      clearSelection()
    }
  }

  // 移动组件（包括其所有子组件）
  const moveComponent = (componentId: string, newParentId?: string) => {
    if (!currentPage.value) return
    
    const component = findComponent(currentPage.value.components, componentId)
    if (!component) return
    
    // 防止拖拽到自己内部
    if (newParentId && isDescendant(componentId, newParentId)) {
      console.warn('不能将组件拖拽到自己的子组件中')
      return
    }
    
    // 记录历史
    addHistory('move_component', { 
      componentId, 
      oldParentId: findParentId(currentPage.value.components, componentId),
      newParentId 
    })
    
    // 从原位置移除
    removeComponentFromPage(currentPage.value.components, componentId)
    
    // 添加到新位置
    if (newParentId) {
      addComponentToParent(currentPage.value.components, newParentId, component)
      const parent = findComponent(currentPage.value.components, newParentId)
      if (parent && parent.children) {
        sortComponentsInPlace(parent.children)
        applyZIndexSequentially(parent.children)
      }
    } else {
      // 添加到根级别
      currentPage.value.components.push(component)
      sortComponentsInPlace(currentPage.value.components)
      applyZIndexSequentially(currentPage.value.components)
    }
    
    // 更新修改时间
    component.updatedAt = new Date().toISOString()
    
    // 保持选中状态
    selectComponent(component)
  }
  
  // 更新组件属性
  const updateComponentProps = (componentId: string, props: Record<string, any>) => {
    console.log('componentId',componentId);
    console.log('props',props);
    console.log('currentPage.value------',currentPage.value);
    if (!currentPage.value) return
    console.log('currentPage.value',currentPage.value);
    const component = findComponent(currentPage.value.components, componentId)
    console.log('component----',component);
    if (!component) return
    
    const oldProps = { ...component.props }
    
    console.log('更新前--props',props);
    console.log('更新前--component.props',component.props);
    // 更新属性
    Object.assign(component, props)

    console.log('component-更新属性后---',component);
    
    // 更新修改时间
    component.updatedAt = new Date().toISOString()
    
    // 强制触发响应式更新
    if (currentPage.value) {
      // 通过重新赋值数组来触发响应式更新
      const components = [...currentPage.value.components]
      currentPage.value.components = components
    }
    
    // 记录历史
    addHistory('update_component_props', { 
      componentId, 
      oldProps, 
      newProps: props 
    })
  }
  
  // 更新组件样式
  const updateComponentStyle = (componentId: string, style: Record<string, any>) => {
    if (!currentPage.value) return
    
    const component = findComponent(currentPage.value.components, componentId)
    if (!component) return
    
    const oldStyle = { ...component.style }
    
    // 更新样式
    Object.assign(component.style || {}, style)
    
    // 更新修改时间
    component.updatedAt = new Date().toISOString()
    
    // 记录历史
    addHistory('update_component_style', { 
      componentId, 
      oldStyle, 
      newStyle: style 
    })
  }
  
  // 更新组件（通用方法，用于更新顶级属性如 name）
  const updateComponent = (componentId: string, updates: Record<string, any>) => {
    if (!currentPage.value) return
    
    const component = findComponent(currentPage.value.components, componentId)
    if (!component) return
    
    console.log('🔄 Designer Store - 更新组件:', { componentId, updates, currentName: component.name })
    
    const oldComponent = { ...component }
    
    // 更新组件属性
    Object.assign(component, updates)
    
    // 更新修改时间
    component.updatedAt = new Date().toISOString()
    
    // 强制触发响应式更新
    if (currentPage.value) {
      // 通过重新赋值数组来触发响应式更新
      const components = [...currentPage.value.components]
      currentPage.value.components = components
    }
    
    console.log('✅ Designer Store - 组件更新完成:', { componentId, newName: component.name })
    
    // 记录历史
    addHistory('update_component', { 
      componentId, 
      oldComponent, 
      newComponent: component 
    })
  }
  
  // 选中组件
  const selectComponent = (component: IComponent, multiSelect = false) => {
    if (multiSelect) {
      selectionState.value.selectedComponents.push(component)
      selectionState.value.isMultiSelect = true
    } else {
      selectionState.value.selectedComponent = component
      selectionState.value.selectedComponents = [component]
      selectionState.value.isMultiSelect = false
    }
  }
  
  // 清除选中状态
  const clearSelection = () => {
    selectionState.value.selectedComponent = undefined
    selectionState.value.selectedComponents = []
    selectionState.value.isMultiSelect = false
  }
  
  // 拖拽状态管理现在由 useDragDropManager 统一处理
  // const setDragState = (state: Partial<IDragState>) => {
  //   Object.assign(dragState.value, state)
  // }
  
  // 处理拖拽操作
  const handleDrop = (component: IComponent, targetId?: string) => {
    // 拖拽逻辑现在由 useDragDropManager 处理
    // 这里只处理业务逻辑
    addComponent(component, targetId)
  }
  
  // 清除拖拽状态
  const clearDragState = () => {
    // 拖拽状态现在由 useDragDropManager 管理
    console.log('拖拽状态已由拖拽管理器统一管理')
  }
  
  // 添加历史记录
  const addHistory = (action: string, data: any, description?: string) => {
    const record: IHistoryRecord = {
      id: generateId(),
      timestamp: Date.now(),
      action,
      data,
      description: description || action
    }
    
    // 移除当前位置之后的历史记录
    history.value = history.value.slice(0, historyIndex.value + 1)
    
    // 添加新记录
    history.value.push(record)
    historyIndex.value = history.value.length - 1
    
    // 限制历史记录数量
    if (history.value.length > 50) {
      history.value.shift()
      historyIndex.value--
    }
  }
  
  // 撤销
  const undo = () => {
    if (!canUndo.value) return
    
    historyIndex.value--
    // TODO: 实现撤销逻辑
  }
  
  // 重做
  const redo = () => {
    if (!canRedo.value) return
    
    historyIndex.value++
    // TODO: 实现重做逻辑
  }
  
  // 创建新项目
  const createProject = (name: string, description?: string) => {
    const project: IProject = {
      id: generateId(),
      name,
      description,
      pages: [],
      widgets: [],
      createdAt: Date.now(),
      updatedAt: Date.now(),
      version: '1.0.0'
    }
    
    currentProject.value = project
    return project
  }
  
  // 创建新页面
  const createPage = (name: string, title: string) => {
    if (!currentProject.value) return null
    
    const page: IPageConfig = {
      id: generateId(),
      name,
      title,
      components: [],
      layout: {
        width: 1920,
        height: 1080,
        background: '#ffffff'
      }
    }
    
    currentProject.value.pages.push(page)
    currentPage.value = page
    
    return page
  }
  
  // 添加子组件到容器
  const addChildComponent = (parentId: string, child: IComponent) => {
    if (!currentPage.value) return null
    
    const parent = findComponent(currentPage.value.components, parentId)
    if (!parent) return null
    
    const newChild = { ...child, id: generateId() }
    if (!parent.children) parent.children = []
    parent.children.push(newChild)
    // 容器内排序与层级
    sortComponentsInPlace(parent.children)
    applyZIndexSequentially(parent.children)
    
    // 记录历史
    addHistory('add_child_component', { 
      parentId, 
      child: newChild,
      previousChildren: [...parent.children]
    })
    
    return newChild
  }
  
  // 从容器移除子组件
  const removeChildComponent = (parentId: string, childId: string) => {
    if (!currentPage.value) return false
    
    const parent = findComponent(currentPage.value.components, parentId)
    if (!parent || !parent.children) return false
    
    const childIndex = parent.children.findIndex(child => child.id === childId)
    if (childIndex === -1) return false
    
    const removedChild = parent.children[childIndex]
    parent.children.splice(childIndex, 1)
    
    // 记录历史
    addHistory('remove_child_component', { 
      parentId, 
      child: removedChild,
      previousChildren: [...parent.children, removedChild]
    })
    
    return true
  }

  // 工具函数
  const generateId = () => `comp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  const findComponent = (components: IComponent[], id: string): IComponent | null => {
    for (const component of components) {
      if (component.id === id) return component
      if (component.children) {
        const found = findComponent(component.children, id)
        if (found) return found
      }
    }
    return null
  }

  // 获取组件（便捷方法）
  const getComponent = (id: string): IComponent | null => {
    if (!currentPage.value) return null
    return findComponent(currentPage.value.components, id)
  }

  const findParentId = (components: IComponent[], id: string): string | undefined => {
    for (const component of components) {
      if (component.children) {
        for (const child of component.children) {
          if (child.id === id) {
            return component.id
          }
          if (child.children) {
            const found = findParentId(child.children, id)
            if (found) return found
          }
        }
      }
    }
    return undefined
  }

  const isDescendant = (childId: string, parentId: string): boolean => {
    const component = findComponent(currentPage.value?.components || [], childId)
    if (!component) return false

    if (component.id === parentId) return true
    if (component.children) {
      for (const child of component.children) {
        if (isDescendant(child.id, parentId)) {
          return true
        }
      }
    }
    return false
  }
  
  const addComponentToParent = (components: IComponent[], parentId: string, newComponent: IComponent) => {
    for (const component of components) {
      if (component.id === parentId) {
        if (!component.children) component.children = []
        component.children.push(newComponent)
        return true
      }
      if (component.children) {
        if (addComponentToParent(component.children, parentId, newComponent)) {
          return true
        }
      }
    }
    return false
  }
  
  const removeComponentFromPage = (components: IComponent[], componentId: string): boolean => {
    for (let i = 0; i < components.length; i++) {
      if (components[i].id === componentId) {
        components.splice(i, 1)
        return true
      }
      if (components[i].children) {
        if (removeComponentFromPage(components[i].children!, componentId)) {
          return true
        }
      }
    }
    return false
  }
  
  const toPxNumber = (value: any, fallback = 0): number => {
    if (value === undefined || value === null) return fallback
    if (typeof value === 'number') return value
    if (typeof value === 'string') {
      const match = value.match(/-?\d+\.?\d*/)
      if (match) return Number(match[0])
    }
    return fallback
  }

  const getFallbackSizeByType = (type: string): { width: number; height: number } => {
    switch (type) {
      case 'image':
        return { width: 300, height: 200 }
      case 'button':
        return { width: 120, height: 40 }
      case 'text':
        return { width: 160, height: 40 }
      case 'container':
        return { width: 300, height: 200 }
      default:
        return { width: 160, height: 40 }
    }
  }

  const getComponentRect = (component: IComponent) => {
    const left = toPxNumber(component.style?.left, Number.POSITIVE_INFINITY)
    const top = toPxNumber(component.style?.top, Number.POSITIVE_INFINITY)
    const fallback = getFallbackSizeByType(component.type)
    const width = toPxNumber(component.style?.width, fallback.width)
    const height = toPxNumber(component.style?.height, fallback.height)
    const centerX = left + width / 2
    const centerY = top + height / 2
    return { left, top, width, height, centerX, centerY }
  }

  const sortComponentsInPlace = (components: IComponent[]) => {
    components.sort((a, b) => {
      const ra = getComponentRect(a)
      const rb = getComponentRect(b)
      // 无位置信息的排到后面
      if (!isFinite(ra.centerY) && !isFinite(rb.centerY)) return 0
      if (!isFinite(ra.centerY)) return 1
      if (!isFinite(rb.centerY)) return -1
      if (ra.centerY !== rb.centerY) return ra.centerY - rb.centerY
      if (ra.centerX !== rb.centerX) return ra.centerX - rb.centerX
      return 0
    })
  }

  const applyZIndexSequentially = (components: IComponent[]) => {
    for (let i = 0; i < components.length; i++) {
      const c = components[i]
      c.style = { ...(c.style || {}), zIndex: i + 1 }
      if (c.children && c.children.length) {
        applyZIndexSequentially(c.children)
      }
    }
  }
  
  return {
    // 状态
    currentProject,
    currentPage,
    widgetLibrary,
    // dragState, // 现在由 useDragDropManager 管理
    selectionState,
    history,
    historyIndex,
    
    // 计算属性
    canUndo,
    canRedo,
    availableWidgets,
    
    // 方法
    addComponent,
    removeComponent,
    moveComponent,
    updateComponentProps,
    updateComponentStyle,
    updateComponent,
    getComponent,
    selectComponent,
    clearSelection,
    // setDragState, // 现在由 useDragDropManager 管理
    handleDrop,
    clearDragState,
    addHistory,
    undo,
    redo,
    createProject,
    createPage,
    addChildComponent,
    removeChildComponent,
    findParentId,
    getWidgetSchema
  }
}) 